
use anyhow::Result;

use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use std::borrow::Borrow;

use std::ops::Sub;
use sqlx::{Pool, MySql, types};
use chrono;

use crate::miner::{JsonRpcResponse, JsonRpcError};
use crate::miner;
use crate::db;
use crate::miner::types::TaskType;
use crate::miner::jobs::SealWork;
use crate::db::SealTaskDetail;

// 注意把数据库清理任务放到任务发放之后执行，避免由于刚刚清理数据库，本应补位的任务未能及时补位，导致多发任务。
pub async fn clean_db_task_not_really_running(pool: &Pool<MySql>, client: &Client<HttpConnector>, url: &str, token: &str) -> Result<()> {
    let ret = miner::jobs::query_jobs_from_miner(client, url, token).await?;
    if let Some(err) = ret.error {
        log::warn!("query jobs from miner error, {:?}", err);
    } else {
        if let Some(array) = ret.result {
            let mut running = HashMap::<u64, SealWork>::new();
            for (w, jobs) in array {
                for j in jobs {
                    if j.run_wait == 0 {
                        running.insert(j.sector.number, j);
                    }
                }
            }
            let mut remove = Vec::<SealTaskDetail>::new();
            let jobs = db::query_db_running_task(pool).await?;
            for j in jobs {
                let find = running.get(&(j.sector_number as u64));
                if  find.is_none() {
                    remove.push(j);
                }
            }
            // log::info!("to be removed job: {:#?}", &remove);
            let rm_task = remove.clone();
            if remove.len() > 0 {
                for j in remove {
                    let r = db::set_db_task_fail(pool, &j).await?;
                    log::info!("complete {}, {}, {}", j.task_type, j.sector_number, r);
                }
            }

            log::info!("to be removed job: {}", &rm_task.len());
            if rm_task.len() > 0 {
                for j in rm_task {
                    log::info!("complete {}, {}", j.sector_number, j.task_type);
                }
            }
        }
    }

    Ok(())
}